/**
* Class to manage debug file
*
* Project: idbcrown
* Author:  TM
* Date:    22/12/2012
*
* History
* ------------------
* 22/12/2012 - TM - Initial version.
*/
 
 
package Util;

import java.io.*;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.*;

import Application.*;

public class libFileDebug
{
 /** Character to byte encoding (Writer->Stream) */
 private static final String ENCODING  = "UTF8";
 private static final String DEBUG_DIR = "DEBUG_TRACE_DIRECTORY_NAME";
 
 /** Debug file definition */
 private FileOutputStream   stream       = null; 
 private OutputStreamWriter writer       = null;
 private PrintWriter        buffer       = null;
 private String             lastFileName = null;
 /** Date format to prefix debug output lines */
 protected DateFormat dateFormat;
 /** Application support */
 protected libApplication appSupport;
 /** Support for singleton */
 protected static libFileDebug debug;
 

 /** Constructor */   
 protected libFileDebug()
 {
   appSupport = libApplication.getInstance();
 }
 
 /** Support for static singleton */
 public static libFileDebug getInstance()
 {
   if (debug == null)
     debug = new libFileDebug();
   
   return debug;  
 }
 
 /** Records debug info into file */
  public void write(String message)
  {
     System.out.println(message);
  }
 
 /** Records Exception info into file */
  public void write(Throwable except)
  {
     except.printStackTrace();
     System.err.println("Error:"+except);
  }
 
 /** Records debug info into file */
  public void writeFile(String message)
  {
	    createDebugFile();  // Create debug file (if it does not already exists)
 	 	 
 	  String debugMessage = getLineHead() + ": " + message;
     buffer.println(debugMessage);        
     try
 	  {
       buffer.flush();
 	  }
 	  catch(Exception e)
 	  {
 	 	   e.printStackTrace();
 	  }
  }
 
 /** Records Exception info into file */
  public void writeFile(Throwable except)
  {
 	 createDebugFile();   // Create debug file (if it does not already exists)
      
 	 String debugMessage = getLineHead() + ": Exception";
    buffer.println(debugMessage);        
 	 except.printStackTrace(buffer);
    buffer.println();
    try
    {
      buffer.flush();
    }
    catch(Exception e)
    {
       e.printStackTrace();
    }
  }
  
 /** Get line header - either date or application Id */
 protected String getLineHead()
 {
   return appSupport.getId();
 }
 
  /** End debug - close file */
  public void done()
  {
   try
   {
     buffer.close();       
 	  writer.close();
     stream.close();
   }
   catch (IOException e)
   {
     appSupport.showErrorMsg(e);
   }        
  }
 	 
  /** Create debug file - check if it already exists (currently implement hourly file) */
  private void createDebugFile()
  {
 	 GregorianCalendar cal = new GregorianCalendar(); 	 	 
 	 String fileName = appSupport.getId() + "$" +  cal.get(cal.YEAR)
 	 	                                    + "-" + (cal.get(cal.MONTH)+1) 
                                         + "-" +  cal.get(cal.DATE)
 	 	                                    + "- "+  cal.get(cal.HOUR_OF_DAY) + "h $" + ".dbg";
       
   String dirPath = appSupport.getConfigNonEmptyValue(DEBUG_DIR) + "\\";

   fileName = dirPath + fileName;

   if (lastFileName != null && lastFileName.equals(fileName))  // Continue writing on same file
     return;
     
   if (lastFileName != null)
   {
     try
     {
       buffer.close();       
       writer.close();
       stream.close();
     }
     catch(IOException except)
     {
     }
   }

 	 try 
 	 {
      stream = new FileOutputStream(fileName, true);
 	 	 writer = new OutputStreamWriter(stream, ENCODING);
 	 	 buffer = new PrintWriter(writer);
 	 	 if (lastFileName == null)
 	 	 {
       buffer.println("------------------------------------");        
       buffer.println(" START - "+(new Date()));
       buffer.println("------------------------------------");        
 	 	 }
     lastFileName = fileName;
 	 }
 	 catch (IOException e)
 	 {
 	 	 appSupport.showErrorMsg(e);
 	 }
  }
  
 /** Initialize debug from config file */
 public void initFromConfig(String config)
 {
 }
 
 /** Initialize debug from argument list */
 public void initFromArguments(String[] args)
 {
 }
  
 /** Debug initialization arguments */
 public String getInitArguments()
 {
   return "";
 }
}
